package csu.web.jpetstore.web.servlet;

import com.alibaba.fastjson.JSON;
import csu.web.jpetstore.domain.Cart;
import csu.web.jpetstore.domain.CartItem;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class AutoUpdataCartServlet extends HttpServlet {

    private static final String CART_FORM = "/WEB-INF/jsp/cart/cart.jsp";

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        HttpSession session=req.getSession();
        Cart cart= (Cart) session.getAttribute("cart");
        String result=null;

        if (cart==null)
            req.getRequestDispatcher(CART_FORM).forward(req,resp);
        Iterator<CartItem> cartItems = cart.getAllCartItems();
        List<CartItem> Result = cart.getCartItemList();
        int size=Result.size();

        int index=Integer.parseInt(req.getParameter("index"));
        String itemId=Result.get(index).getItem().getItemId();
        int quantity=Integer.parseInt(req.getParameter("count"));

        cart.setQuantityByItemId(itemId,quantity);

        if(quantity<1){
                Result.remove(index);
        }
//        while(cartItems.hasNext()){
//            CartItem cartItem = (CartItem) cartItems.next();
//            String itemId = cartItem.getItem().getItemId();
//            int i=0;
//            CartItem cartItem1=Result.get(i);
//            String itemId1=cartItem1.getItem().getItemId();
//            try {
//                String quantityString = req.getParameter(itemId1);
//                int quantity = Integer.parseInt(req.getParameter("count"));
//
//                cart.setQuantityByItemId(itemId1, quantity);
//                if (quantity < 1) {
//                    cartItems.remove();
//                    Result.remove(i);
//                }
//                i++;
//            } catch (Exception e) {
//                //ignore parse exceptions on purpose
//            }
//        }
        result= JSON.toJSONString(Result);
        System.out.println(result);

        resp.setContentType("text/json");
        PrintWriter out=resp.getWriter();
        out.println(result);
    }
}
